﻿"use strict"

/*
 *
 * TODO :
- centrer heure
 *
 *
 *
 */


//Prévision horaire par jours
function HourlyForecast(hour, iconUrl, temp, precipitation, humidity, windSpeed, date, condition) {
	this.hour = hour;
	this.iconUrl = iconUrl;
	this.temp = temp;
	this.precipitation = precipitation;
	this.humidity = humidity;
	this.windSpeed = windSpeed;
	this.date = date;
	this.condition = condition;
}

//Classe représentant le jour de la semaine et une liste de ***
function DayForecast(nom, hourlyForecast) {
	this.nom = nom;
	this.hourlyForecast = hourlyForecast;
}

/*** Gestion de la Request ***/
var Request = {
	parameter : function (name) {
		return this.parameters()[name];
	},

	parameters : function () {
		var result = {};
		var url = window.location.href;
		var parameters = url.slice(url.indexOf('?') + 1).split('&');

		for (var i = 0; i < parameters.length; i++) {
			var parameter = parameters[i].split('=');
			result[parameter[0]] = parameter[1];
		}
		return result;
	}
}

angular.module('meteoApp', [])
.controller('MeteoController', ['$scope', '$http', function ($scope, $http) {

			//Initiliatlise Google Map avec la ville de Lille par défaut
			$scope.mapLocation = {
				center : {
					lat : 50.56999969,
					lng : 3.09999990
				}
			};

			//Favorites
			$scope.cities = getCities();

			$scope.addCity = function (city) {
				addCityInCookie(city);
				$scope.cities = getCities();
			};

			$scope.deleteCity = function (city) {
				deleteCityInCookie(city);
				$scope.cities = getCities();
			};

			//Last Update Time
			$scope.lastUpdateTime = "LastUpdateTime";

			//Temps
			$scope.currentLocation = "...";
			$scope.currentObservationWeather = "...";
			$scope.currentObservationIcon_url = "";
			$scope.relativeHumidity = "0";
			$scope.pressure = "0";
			$scope.sunrise = "0h00";
			$scope.sunset = "0h00";

			//Température
			$scope.currentObservationTemp_c = 0;
			$scope.currentObservationFeelslike_c = 0;
			$scope.currentObservationdewpoint_c = 0;
			$scope.currentObservationUV = 0;

			//Vents
			$scope.currentObservationWind_mph = 0;
			$scope.currentObservationWind_dir = 0;

			//Sélection du pays et de la ville
			var query = Request.parameter('query');

			var country,
			city;

			if (query != undefined) {
				query = query.replace("%2C", ",");
				var queryAnalyser = query.split(",");
				city = queryAnalyser[0];
				country = queryAnalyser[1];
			}

			if (country == undefined)
				country = 'France';
			if (city == undefined)
				city = 'Lille';

			city = city.replace("+", "%20");

			//Sélection Webcams
			var webcamRequest = Request.parameter('webcams');
			if (webcamRequest == undefined || webcamRequest != "true")
				webcamRequest = "";
			else
				webcamRequest = "/webcams";

			//Call Ajax

			//d98c1e0f21410f6c
			//812f7187ba5b899c
			$http.jsonp("http://api.wunderground.com/api/d98c1e0f21410f6c" + webcamRequest + "/hourly7day/geolookup/astronomy/conditions/alerts/lang:FR/q/" + country + "/" + city + ".json?callback=JSON_CALLBACK")
			.success(function (data, status, headers, config) {

				//Gestion des erreurs
				
				if(data.response.error)
				{
						
					//Gestion des erreurs
					var description = data.response.error.description;
					var type = data.response.error.type;
					
					if(type == "querynotfound")
						type = "0 résultat";
					if(description == "No cities match your search query")
						description = "Aucune ville ne correspond à votre recherche";
					
					$scope.error = type + ' : ' + description;
					return;				
				}
				
			
				//Last Update Time
				$scope.lastUpdateTime = data.current_observation.observation_time.replace("Ã©", "é").replace('Ã»', 'û') + " - " + data.location.city + " (" + data.location.country_name + ") ";

				//Temps
				$scope.currentLocation = data.location.city;
				$scope.currentObservationWeather = data.current_observation.weather;
				$scope.currentObservationIcon_url = data.current_observation.icon_url;
				$scope.relativeHumidity = data.current_observation.relative_humidity;
				$scope.pressure = data.current_observation.pressure_mb / 10;
				$scope.sunrise = data.moon_phase.sunrise.hour + "h" + data.moon_phase.sunrise.minute;
				$scope.sunset = data.moon_phase.sunset.hour + "h" + data.moon_phase.sunset.minute;

				//Température
				$scope.currentObservationTemp_c = data.current_observation.temp_c;
				$scope.currentObservationFeelslike_c = data.current_observation.feelslike_c;
				$scope.currentObservationdewpoint_c = data.current_observation.dewpoint_c;
				$scope.currentObservationUV = data.current_observation.UV;

				//Vents
				$scope.currentObservationWind_mph = parseInt(data.current_observation.wind_mph * 1.609344) + " km/h";
				$scope.currentObservationWind_dir = data.current_observation.wind_dir;

				/*******************************************************************************************/
				/***************************************** --- hourly7day --- ******************************/
				/*******************************************************************************************/

				//Days
				$scope.daysForecast = [];
				var date = new Date();
				var currentDay = date.getDate();
				var initialDate = currentDay;
				var hourlyForecastDay = [];

				angular.forEach(data.hourly_forecast, function (hourlyForecast, index) {

					var mday = hourlyForecast.FCTTIME.mday;
					var mon = hourlyForecast.FCTTIME.mon;
					var hour = hourlyForecast.FCTTIME.hour + 'h';

					if (hourlyForecast.FCTTIME.hour > 5)
						hourlyForecastDay.push(new HourlyForecast(hour, hourlyForecast.icon_url, hourlyForecast.temp.metric, hourlyForecast.pop, hourlyForecast.humidity , hourlyForecast.wspd.metric , mday + "/" + mon + " - " + hour, hourlyForecast.condition));

					if (hourlyForecast.FCTTIME.hour == 23) {

						var day = "";
						if (initialDate == currentDay)
							day += "Aujourd'hui - ";
						else if (initialDate + 1 == currentDay)
							day += "Demain - ";
						else if (initialDate + 2 == currentDay)
							day += "Après demain - ";

						day += hourlyForecast.FCTTIME.weekday_name + " " + hourlyForecast.FCTTIME.mday + " " + hourlyForecast.FCTTIME.month_name;

						$scope.daysForecast.push(new DayForecast(day, hourlyForecastDay));
						hourlyForecastDay = [];

						currentDay += 1;
					}
				});

				/*******************************************************************************************/
				/***************************************** --- Alerts --- ******************************/
				/*******************************************************************************************/

				$scope.alerts  = "";
				if(data.alerts.length > 0)
				{
					for (var i=0;i<data.alerts.length;i++)
					{
						$scope.alerts += data.alerts[i].level_meteoalarm_name + " : " + data.alerts[i].description + ". " ;
					}
				}
				
				/*******************************************************************************************/
				/***************************************** --- Webcams --- ******************************/
				/*******************************************************************************************/
				if (data.webcams != undefined)
					$scope.webcams = data.webcams;

				/*******************************************************************************************/
				/***************************************** --- MAP --- ******************************/
				/*******************************************************************************************/

				$scope.mapLocation = {
					center : {
						lat : data.location.lat,
						lng : data.location.lon
					}
				};

				/*******************************************************************************************/
				/***************************************** --- ZOOM --- ******************************/
				/*******************************************************************************************/

				/*******************************************************************************************/
				/************************************ --- Pluie à une heure --- ****************************/
				/*******************************************************************************************/

				$("#rainForecast").ready(function () {
					$.getJSON('http://meteodesquiens.azurewebsites.net/Services/ForecastService.svc/GetForecast/' + city + '?callback=?', null, function (dataRain) {

						if (!dataRain.Error) {

							var colors = new Array();
							var arrayRainForecast = new Array();
							for (var i = 0; i < dataRain.RainForecast.length; i++) {

								arrayRainForecast[i] = [dataRain.RainForecast[i].Forecast, dataRain.RainForecast[i].Percent];

								if (arrayRainForecast[i][0] == "Pas de precipitations")
									colors[i] = '#f2e513';
								else if (arrayRainForecast[i][0] == "Precipitations faibles")
									colors[i] = '#CCCCCC';
								else if (arrayRainForecast[i][0].indexOf("mod") != -1) //Pluie modérée
									colors[i] = '#878585';
								else if (arrayRainForecast[i][0] == "Precipitations fortes")
									colors[i] = '#353535';
								else
									colors[i] = '#FFFFFF';
							}

							$("#rainForecast").ready(function () {
								var plot3 = $.jqplot('rainForecast', [arrayRainForecast], {
										seriesDefaults : {

											// make this a donut chart.
											renderer : $.jqplot.DonutRenderer,
											rendererOptions : {
												// Donut's can be cut into slices like pies.
												sliceMargin : 3,
												// Pies and donuts can start at any arbitrary angle.
												startAngle : -90,
												padding : 2,
												innerDiameter : 10,
												showDataLabels : false,
												// By default, data labels show the percentage of the donut/pie.
												// You can show the data 'value' or data 'label' instead.
												dataLabels : 'label'
											}
										},
										legend : {
											show : false,

											border : 'none'
										},
										grid : {
											borderWidth : 0,
											shadow : false,
											background : '#FFFFFF'
										},
										title : 'Pluie à 1h',
										seriesColors : colors
									});
							});
						} else {
							//alert(data.Error);
						}
					});
				});

				/*******************************************************************************************/
				/***************************************** --- FIN --- ******************************/
				/*******************************************************************************************/

			})
			.error(function (data, status, headers, config) {
				alert("Error call API");
	
				
				
				
			});

		}
	])

/*******************************************************************************************/
/***************************************** --- MAP --- ******************************/
/*******************************************************************************************/

.directive('map', [
		function () {
			return {
				restrict : 'E',
				scope : {
					center : "="
				},
				controller : function ($scope) {},
				link : function (scope, element, attrs) {
					var el = document.createElement("div");
					el.style.width = "100%";
					el.style.height = "100%";
					element.prepend(el);

					var mapOptions = {
						center : scope.center,
						zoom : 12,
						mapTypeId : google.maps.MapTypeId.ROADMAP,
						streetViewControl : false
					};

					var map = new google.maps.Map(el, mapOptions);
			
					scope.$watch('center', function (value) {
						if (scope.center.lat != map.getCenter().lat() || scope.center.lng != map.getCenter().lng()) {
							map.setCenter(new google.maps.LatLng(+scope.center.lat, +scope.center.lng));
						}
					}, true)

				}
			};
		}
	]);
